<?php
/**
 * Created by PhpStorm.
 * User: dust2
 * Date: 15-1-29
 * Time: 下午3:22
 */

namespace Libraries\EventHandler;

use Auth;
use Notification;
use Project;
use Project_Member;

/**
 * 项目分享通知事件处理器
 * Class ProjectSharingEventHandler
 * @package Libraries\EventHandler
 */
class ProjectSharingEventHandler extends AbstractEventHandler
{

    protected function config()
    {
        $eloquentAction = [
            'created' => '@sharingCreated'
        ];
        $this->setEloquentEvent($eloquentAction, 'ProjectSharing');
    }

    /**
     * 分享创建时触发通知创建、通知发送
     * @param $event
     */
    public function sharingCreated($event)
    {
        $title = $event['name'];
        $content = Auth::user()['username']. ' 新建了分享'. $event['title'];

        $newNotify = $this->createNotification($event, $title, $content);
        $this->sendNotification($event['project_id'], $newNotify['id']);
    }

    /**
     * 创建新的通知，自动设置一些固定字段的值
     *
     * @param $event array 消息源
     * @param $title string 通知的标题
     * @param $content string 通知的内容
     * @return Illuminate\Database\Eloquent\Model 新创建的通知模型
     */
    protected function createNotification($event, $title, $content)
    {
        $notifyData['type_id'] = 5;
        $notifyData['trigger_id'] = Auth::user()['id'];
        $notifyData['source_id'] = $event['id'];
        $notifyData['project_id'] = $event['project_id'];

        $notifyData['title'] = $title;
        $notifyData['content'] = $content;

        $notifyData['created_at'] = date('Y-m-d');
        $notifyData['updated_at'] = date('Y-m-d');

        return Notification::create($notifyData);

    }

    /**
     * 给接受者发送通知
     *
     * @param $sourceId int 事件源的id
     * @param $notificationId int 通知的id
     */
    protected function sendNotification($sourceId, $notificationId)
    {

        $receiverIds = array_fetch(
            Project_Member::where('project_id', $sourceId)->get(['member_id'])->toArray(),
            'member_id'
        );

        array_push($receiverIds, Project::findOrFail($sourceId)['creater_id']);

        $this->storeToInbox($notificationId, $receiverIds);
    }

    protected $handlerName = 'ProjectSharingEventHandler';
}
